import React, { useEffect, useState } from 'react';
import GopherProps from '../objects/internal/GopherProps';
import { PaginationResult } from '../objects/internal/PaginationResult';
import { Table } from 'antd';

export interface TableProps extends GopherProps {
	dataFormat: Array<{ title: string, dataIndex: string, key?: string }>;
	fetch: (page: number, size: number) => Promise<PaginationResult>;
	rowKey?: string;

	onSelection: (key: React.Key[], selectedRows: object[]) => void;
}

interface Pagination {
	current: number;
	pageSize: number;
	total: number;
}

interface TableState {
	loading: boolean;
	data: Array<object>;
	pagination: Pagination;
}

export default function AsyncPaginatedTable(props: TableProps) {
	const [state, setState] = useState<TableState>({
		loading: true,
		data: [],
		pagination: {
			current: 1,
			pageSize: 10,
			total: 0,
		},
	});

	const onTableRefresh = (pagination: Partial<Pagination>) => {
		setState({
			loading: true,
			data: [],
			pagination: {
				current: pagination.current || 1,
				pageSize: pagination.pageSize || 10,
				total: 0,
			},
		});
	};

	useEffect(() => {
		if (state.loading) {
			props.fetch(state.pagination.current || 1, state.pagination.pageSize).then(data => {
				setState({
					loading: false,
					data: data.data,
					pagination: {
						current: state.pagination.current,
						pageSize: state.pagination.pageSize,
						total: data.total,
					},
				});
			});
		}
	});

	return (
		<Table columns={props.dataFormat} dataSource={state.data} rowKey={props.rowKey || '_id'}
			   pagination={state.pagination} loading={state.loading} onChange={onTableRefresh}
			   rowSelection={{type: 'radio', onChange: props.onSelection}}/>
	);
}

